<!--
 * @Author: tcosfish
 * @Date: 2022-08-25 15:59:08
 * @LastEditors: tcosfish
 * @LastEditTime: 2022-08-26 16:26:02
 * @FilePath: \ry-frontend\src\components\Upload.vue
-->
<script setup lang="ts">
import { ElUpload, ElMessage, ElIcon } from "element-plus"
import { UploadFilled } from "@element-plus/icons-vue"
import type { UploadProps, UploadUserFile, UploadInstance } from "element-plus"
import { ref } from "vue"

defineProps<{
  uploadAction: string
  uploadParams: Record<string, any>
}>()

const elUploadRef = ref<UploadInstance>()

const fileType = [
  "application/vnd.ms-excel",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
]
const fileNameCheck = ["科目余额", "分录"]
const fileList = ref<UploadUserFile[]>([])

// 上传之前的处理
const beforeUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (fileType.includes(rawFile.type)) {
    return true
  } else {
    ElMessage({
      message: "请选择xlsx, xls, csv格式文件上传",
      grouping: true,
      type: "error",
    })
    return false
  }
}

const successState: UploadProps["onSuccess"] = (response) => {
  console.log(response)
}

const submitFile = () => {
  elUploadRef.value?.submit()
}

defineExpose({
  submitFile,
})
</script>

<template>
  <el-upload
    ref="elUploadRef"
    class="ry-el-upload"
    v-model:file-list="fileList"
    method="post"
    :data="uploadParams"
    :action="uploadAction"
    :before-upload="beforeUpload"
    :on-success="successState"
    :auto-upload="false"
    multiple
    drag
  >
    <template #trigger>
      <el-icon :size="40" :color="'#a4adeb'"><upload-filled /></el-icon>
      <div class="ry-el-upload-text">选择<em>文件</em></div>
    </template>
    <template #tip> 仅支持上传 xlsx, xls, csv 格式文件 </template>
  </el-upload>
</template>

<style scoped lang="scss">
.ry-el-upload {
  width: 100%;
  &-text em {
    color: rgba($color: #424c8d, $alpha: 1);
  }
}
</style>
